<template>
	<view>
		<firstConnect v-if="isFirst" :device-type="deviceType" :deviceStatus="deviceStatus" @startUse="startUse"
			@retry="retry"></firstConnect>
		<template v-else>
			<view class="toptip flex align-center justify-between" v-if="!isConnected">
				<text>{{ blueState ? '当前设备未连接，请连接设备' : '需要开启蓝牙，连接设备' }}</text>
				<view class="btn flex align-center" @click="_startBluetoothDevicesDiscovery" v-if="blueState">
					<u-loading-icon color="#fff" :show="deviceStatus == 0 || deviceStatus == 1"></u-loading-icon>
					<text>去连接</text>
				</view>
			</view>
			<view class="startWork">
				<div class="blueState u-flex  u-flex-column ">
				<image src="/static/device/bluetooth.png" mode="widthFix" v-if="deviceStatus!=2||deviceRunStatus=='0b'"></image>
				<image src="/static/device/bluetooth_cur.png" mode="widthFix" v-else></image>
				<span class="name" :class="{'active':deviceStatus==2&&deviceRunStatus!='0b'}">{{deviceStatus==2&&deviceRunStatus!='0b'?"已连接":"未连接"}}</span>
				</div>
				<dmChart ref="dmChart"></dmChart>
				<!---->
				<view v-if="isConnected && deviceRunStatus == '04'">
					<!-- <view class="tip">{{ deviceData > 0 ? '' : '测量失败' }}</view> -->
					<template v-if="deviceData.result > 0">
						<view class="stepbox">
							<dmStep size="lg" :result="deviceData.result"></dmStep>
						</view>
						<view class="flex result">
							<view class="flex-sub item">
								<view>血糖值</view>
								<view class="u-margin-top-20">
									<text class="num">{{ deviceData.result }}</text>
									<text class="unit">mmol/L</text>
								</view>
							</view>
							<view class="flex-sub item">
								<view>检测时段</view>
								<view class="u-margin-top-20">
									<text class="num" style="font-size: 40rpx;">{{ deviceData.testNutritionalTime }}</text>
									<text class="unit"></text>
								</view>
							</view>
						</view>
						<view class="u-m-t-30">
							<u-button shape="circle" type="primary" text="保存" @click="save"></u-button>
						</view>
					</template>
				</view>
				<view class="tip u-m-t-20">{{tip}}</view>
			</view>
		</template>
		<!-- <view>{{ textLog }}</view> -->
		<!-- <view>{{foundTimer}}</view> -->
		<!-- <view>{{JSON.stringify(devices)}}</view> -->
		<deviceModal ref="deviceModal" :devicesList="devices" @connectToDevice="connectToDevice"></deviceModal>
	</view>
</template>

<script>
	let authParams = {
		appKey: '5d639652e46cee7d9a905f2ee09d9542', // 云平台为客户的机构生成的key
		appIdentifier: 'wxb6950ef8a3cfbc78' // 小程序appId 或者 uniapp的AppId
	};
	import firstConnect from './components/firstConnect';
	import deviceModal from './components/deviceModal';
	import {
		ab2hex
	} from '@/utils/util.js';
	import {
		mapState
	} from 'vuex';
	let foundTimer = null;
	import stompMixin from '@/common/stompMixin.js';
	import mixin from './mixin.js';
	import dmChart from './components/dmChart';
	import dmStep from '@/components/dmStep';
	export default {
		data() {
			return {
				devices: [],
				textLog: '',
				adapterState: false,
				blueState: false, //蓝牙连接状态
				deviceStatus: 0,
				deviceType: 'GM501',
				isConnected: false,
				isFirst: true,
				deviceMac: '',
				deviceTypeId: '',
				deviceData: {
					result: 5, // 结果值
					formatTime: '', // 测量时间
					indicatorOriginalResult: '', //真实值
					testNutritionalTime: '' // 时间代码
				},
				tip: '',
				deviceRunStatus: 0
			};
		},
		mixins: [stompMixin, mixin],
		components: {
			firstConnect,
			deviceModal,
			dmChart,
			dmStep
		},
		onLoad(optioin) {
			this.deviceType = optioin.deviceType;
			if (optioin.deviceTypeId) {
				this.deviceTypeId = optioin.deviceTypeId;
				this.isFirst = true;
			} else {
				this.deviceMac = optioin.deviceMac;
				this.isFirst = false;
			}
			this._openBluetoothAdapter();
		},
		onUnload() {
			// 不在当前页面的时候断开连接
			this.disconnectToDevice();
			if (foundTimer || this.deviceStatus == 0) {
				this.clearfoundTimer();
			}
		},
		computed: {
			...mapState(['userInfo', 'curAccount','doctorId'])
		},
		watch: {
			adapterState(newVal, oldVal) {
				if (newVal && !this.blueState) {
					this.blueState = true; //设置蓝牙初始化成功了
					this.deviceStatus = -1;
					if (this.isFirst) {
						this._startBluetoothDevicesDiscovery();
					}
				}
			},
			devices(newVal, oldVal) {
				if (newVal.length > 0) {
					if (this.isFirst) {
						this.$refs.deviceModal.show = true;
					} else {
						this.deviceStatus = 1;
						this.connectToDevice(0);
						clearTimeout(foundTimer);
						foundTimer = null;
					}
				}
			}
		},
		methods: {
			/**
			 * @description: 第一步 初始化蓝牙模块
			 * @param {*}
			 * @return {*}
			 */
			_openBluetoothAdapter() {
				let _this = this;
				uni.openBluetoothAdapter({
					success() {
						_this._getBlueAdapterState();
					},
					fail: err => {
						// 初始化失败，除了可能是没开蓝牙，还可能是用户的手机需要给微信授权蓝牙功能，这可以通过err的state状态为3或4来判断
						console.log('蓝牙初始化错误，3未授权，4未开启', err.state);
						if (err.state === 3 || err.state === 4) {
							wx.showModal({
								title: '蓝牙未授权',
								content: '请前往手机-设置-隐私-蓝牙，对您的微信授权蓝牙功能',
								showCancel: false,
								confirmText: '知道了'
							});
						} else {
							wx.showModal({
								title: '蓝牙未开启',
								content: '请前往手机设置打开蓝牙',
								showCancel: false,
								confirmText: '知道了'
							});
						}
					}
				});
			},
			/**
			 * @description: 第二步 获取本机蓝牙适配器状态
			 * @param {*}
			 * @return {*}
			 */
			_getBlueAdapterState() {
				let _this = this;
				uni.getBluetoothAdapterState({
					success(data) {
						if (data.available) {
							_this.adapterState = true;
							//_this._startBluetoothDevicesDiscovery();
						}
					},
					fail(err) {
						console.log('getBluetoothAdapterState', err);
						_this._onBluetoothAdapterStateChange();
					}
				});
			},
			_onBluetoothAdapterStateChange() {
				uni.onBluetoothAdapterStateChange(res => {
					let {
						code,
						data,
						msg
					} = res;
					if (code == 0) {
						if (data.available) {
							this.adapterState = true;
							//this._startBluetoothDevicesDiscovery();
						}
					}
				});
			},
			/**
			 * @description: 第三步 开始搜索蓝牙设备
			 * @param {*}
			 * @return {*}
			 */
			_startBluetoothDevicesDiscovery() {
				this.deviceStatus = 0;
				//5s没有找到设备，就提示没有发现设备
				foundTimer = setTimeout(() => {
					this.clearfoundTimer();
				}, 5000);
				let _this = this;
				uni.startBluetoothDevicesDiscovery({
					services: [],
					allowDuplicatesKey: false,
					interval: 1000,
					success(res) {
						_this._onBluetoothDeviceFound();
					},
					fail(err) {
						console.log('startBluetoothDevicesDiscovery', err);
					}
				});
			},
			/**
			 * @description: 第四步 监听搜索到蓝牙设备
			 * @param {*}
			 * @return {*}
			 */
			_onBluetoothDeviceFound() {
				let _this = this;
				// uni.onBluetoothDeviceFound(res => {
				// 	uni.getBluetoothDevices({
				// 		success: res => {
				// 			console.log('res.devices', res.devices)
				// 			this.foundDevices = res.devices.filter((item) =>
				// 				this
				// 				.deviceFoundFilter(item))
				// 			// this.foundDevices = this.foundDevices.concat(res.devices.filter((item) => this
				// 			// 	.deviceFoundFilter(item) && (this.foundDevices.indexOf(item) == -1)))
				// 		}
				// 	})
				// })
				uni.onBluetoothDeviceFound(data => {
					uni.getBluetoothDevices({
						success: data => {
							let deviceArr = [..._this.devices];
							console.log('搜索记录1', data.deviceArr);
							console.log('搜索记录2', data.devices);
							if (data.devices.length) {
								data.devices.map(v => {
									if (v.name || v.localName) {
										let blueName = v.name || v.localName;
										if (/(SN-7A)/.test(blueName)) {
											// if (utils.prefixInName(_this.perfix, blueName)) {
											if (blueName == 'Oximeter-BLE') {
												console.error(ab2hex(v.advertisData).toUpperCase());
											}
											let macAddrStr = ab2hex(v.advertisData)
												.toUpperCase()
												.replace(/(.{2})/g, '$1:');
											if (blueName == 'HeartRate Scale') {
												console.log(macAddrStr);
											}
											if (blueName == 'QN-HS') {
												v.macAddr = macAddrStr.substring(macAddrStr.length - 21, macAddrStr.length - 3);
												v.macAddr = [...v.macAddr].reverse().join('');
											} else {
												v.macAddr = macAddrStr.substring(macAddrStr.length - 18, macAddrStr.length - 1);
											}
											let idx = deviceArr.findIndex(d => {
												return d.deviceId == v.deviceId;
											});
											// console.log('搜索到的设备', deviceArr)
											if (idx == -1) {
												deviceArr.push(v);
											}
										}
									}
									return v;
								});
								if (this.deviceMac) {
									deviceArr = deviceArr.filter(item => item.deviceId == this.deviceMac)
								}
								_this.devices = [...deviceArr];

							}
						}
					})

				});
			},

			_stopBluetoothDevicesDiscovery() {
				uni.stopBluetoothDevicesDiscovery();
			},
			connectToDevice(index) {
				let info = this.devices[index];
				clearTimeout(foundTimer);
				foundTimer = null;
				this.createBLEConnection(info)
			},
			createBLEConnection: function(ds) {
				let bindDevice = {
					macId: ds.deviceId,
					macAddr: ds.macAddr,
					deviceName: ds.name || ds.localName,
					name: ds.name || ds.localName
				};
				this._stopBluetoothDevicesDiscovery();
				this.connectOnce(ds.deviceId, ds.macAddr, bindDevice);
			},
			connectOnce(macId, macAddr, bindDevice) {
				let params = authParams;
				params.deviceMac = macAddr;
				this.$snGm501.createBLEConnection(
					macId,
					res => {
						console.log(3, res);
						this.isConnected = true;
						this.connectedDevice = bindDevice;
						this.deviceStatus = 2;
						if (this.isFirst) {
							this.addDevice();
						} else {
							this._onBLECharacteristicValueChange();
						}
					},
					uni,
					20000,
					params
				);
			},
			_onBLECharacteristicValueChange() {
				uni.onBLECharacteristicValueChange(res => {
					let obj = this.$snGm501.parseData(res);
					// let obj = {
					// 	"code": "04",
					// 	"msg": "直接测量",
					// 	"data": {
					// 		"result": 5.6,
					// 		"time": 1744550757000,
					// 		"formatTime": "2025-04-13 21:25:57",
					// 		"data": [83, 78, 27, 32, 1, 4, 0, 1, 23, 9, 27, 21, 7, 46, 2, 231, 146, 67, 1, 0, 0, 0, 56, 16, 0, 0,
					// 			0, 6, 22, 233, 13, 10
					// 		],
					// 		"order": 1,
					// 		"simpleType": "血液",
					// 		"testNutritionalTime": "随机",
					// 		"hematocrit": 0,
					// 		"unit": "mmol/L",
					// 		"indicatorOriginalResult": 5.6,
					// 		"isHigh": false,
					// 		"calibrationCode": "C22",
					// 		"predictorFlag": "0",
					// 		"timeCalibrationFlags": "1",
					// 		"firstDataFlagAfterPowerFailure": "1",
					// 		"historyTimeCalibrationFlags": "0",
					// 		"type": "GLU"
					// 	}
					// }
					console.log('obj', obj)
					let {
						code,
						msg,
						data
					} = obj;
					if (obj && typeof obj === 'object') {
						this.textLog += JSON.stringify(obj) + '\n';
						this.tip = msg;
						this.deviceRunStatus = code;
						if (code == '04') {
							for (var key in this.deviceData) {
								this.deviceData[key] = data[key]
							}
							this.$refs.dmChart && this.$refs.dmChart.getServerData(this.deviceData.result);
						}
					}
				});
			},
			startUse() {
				this.isFirst = false;
				this._onBLECharacteristicValueChange();
			},
			retry() {
				this.deviceStatus = 0;
				this.devicesDiscovery();
			},
			clearfoundTimer() {
				this._stopBluetoothDevicesDiscovery();
				clearTimeout(foundTimer);
				foundTimer = null;
				if (this.devices && this.isFirst) {
					//this.deviceStatus = 1;
				} else {
					this.deviceStatus = 3;
				}
			},
			save() {
				/* this.send(
					JSON.stringify({
						detailId: this.curAccount.detailId,
						type: this.deviceType,
						data: this.deviceData
					})
				); */
				this.send_testtwo(
					JSON.stringify({
						oprDocterID:this.doctorId,
						patientId:this.curAccount.patientId,
						type: this.deviceType,
						data: this.deviceData
					})
				);
				uni.showToast({
					title: '保存成功',
					icon: 'none'
				})
				this.$Router.replaceAll({
					path: '/pages/measure/measure'
				});
			},
			// 断开连接设备
			disconnectToDevice() {
				if (!!this.connectedDevice) {
					wx.closeBLEConnection({
						deviceId: this.connectedDevice.deviceId,
						success: () => {
							this.connectedDevice = null
						},
						fail: (res) => {
							console.log('失败了', res, this.connectedDevice)
						},
						complete: () => {
							if (this.adapterState) {
								wx.closeBluetoothAdapter()
							}
							//this.bleReset();
						}
					});

				} else {
					if (this.adapterState) {
						wx.closeBluetoothAdapter()
					}
					//this.bleReset()
				}

			}
		}
	};
</script>


<style scoped lang="scss">
	.pageview {
		background: #f2f2f2;
		height: 100vh;
		overflow: auto;
	}

	.startWork {
		width: 600upx;
		margin: 0 auto;
		padding-top: 180upx;
		.blueState{
			position: absolute;
			left: 30upx;
			top: 140upx;
			//top: 160upx;
			image{
				width: 60upx;
				height: 60upx;
				margin: 0 auto;
			}
			.name{
				color: #999;
				margin-top: 10upx;
				font-size: 30upx;
				&.active{
					color: #36B7AB;
				}
			}
		}
		.imgbox {
			width: 400upx;
			margin: 0 auto 70upx;
		}

		.tip {
			text-align: center;
			margin-bottom: 10upx;
		}

		.stepbox {
			margin-top: 50upx;
		}

		.result {
			background: #fff;
			border-radius: 16upx;
			font-size: 28upx;
			color: #a5adae;
			padding: 30upx 20upx;
			margin-top: 50upx;

			.item {
				padding: 0 16upx;
			}

			.num {
				color: #243138;
				font-size: 46upx;
				font-weight: bold;
			}

			.unit {
				color: #374547;
				font-size: 24upx;
				margin-left: 10upx;
			}
		}
	}

	.toptip {
		background: #fff;
		padding: 20upx;
		position: absolute;
		top: 0;
		left: 0;
		right: 0;

		.btn {
			background: $u-primary;
			padding: 0 20upx;
			color: #fff;
			border-radius: 50upx;
			line-height: 60upx;
		}
	}
</style>